"ui";
ui.layout(
    <drawer id="drawer">
        <vertical>
            <appbar>
                <toolbar bg="#FF5c50e6" id="toolbar" title="超级大蚂蚁UI版v1.0.0" paddingTop="2dp" h="auto" >
                </toolbar>
                <tabs id="tabs" />
            </appbar>
            <viewpager id="viewpager">
                {/* 第一个Frame */}
                <frame>
                    <scroll>
                        <vertical gravity="center">
                            <horizontal  gravity="center_vertical" padding="5 5" >
                                <View bg="#00BFFF" h="*" w="10"  ></View>
                                <vertical padding="10 8" h="auto" w="0" layout_weight="1">
                                    <text w="auto" textColor="#222222" textSize="14sp" text="今日头条极速版" />
                                    <text w="auto" textColor="#999999" textSize="12sp" text="自动阅读、领金币、宝箱" />
                                </vertical>
                                <checkbox id="toutiao" marginLeft="4" marginRight="6" checked="true" />
                            </horizontal>
 
                            <horizontal  gravity="center_vertical" padding="5 5" >
                                <View bg="#00FFFF" h="*" w="10"  ></View>
                                <vertical padding="10 8" h="auto" w="0" layout_weight="1">
                                    <text w="auto" textColor="#222222" textSize="14sp" text="抖音短视频" />
                                    <text w="auto" textColor="#999999" textSize="12sp" text="滑动、关注、点赞、评论，自动化一体" />
                                </vertical> 
                                <checkbox id="douyin" marginLeft="4" marginRight="6" checked="false" />
                            </horizontal>
 
                           
 
                           
                            <horizontal gravity="right">
                                <button style="Widget.AppCompat.Button.Colored"  id="wool" text="启动" padding="12dp" w="auto" />
                                <button style="Widget.AppCompat.Button.Colored"  id="close" text="关闭线程" />
                            </horizontal>
                        </vertical>
                    </scroll>
                </frame>
                {/* 第二个Frame */}
                <frame>
                    <scroll>
                        <vertical>
                            
                            <horizontal  gravity="center_vertical" padding="5 5" >
                                <View bg="#4876FF" h="*" w="10"  ></View>
                                <text w="auto"  padding="8 8 8 8" textColor="#222222" textSize="14sp" text="遍历次数:" />
                                <input id="txtForeachTimes" text="10"  hint="App被打开的次数"  textSize="13sp"  inputType="number" />
                            </horizontal>
 
                            <horizontal  gravity="center_vertical" padding="5 5" >
                                <View bg="#4876FF" h="*" w="10"  ></View>
                                <text w="auto"  padding="8 8 8 8" textColor="#222222" textSize="14sp" text="滑动屏幕次数:" />
                                <input id="txtScreenSileTimes" text="100"  hint="滑动屏幕次数"  textSize="13sp"  inputType="number" />
                            </horizontal>
 
                            <horizontal  gravity="center_vertical" padding="5 5" >
                                <View bg="#4876FF" h="*" w="10"  ></View>
                                <text w="auto"  padding="8 8 8 8" textColor="#222222" textSize="14sp" text="屏幕滑动时间间隔(秒):" />
                                <input id="txtScreenSileTimesInterval" text="15"  hint="滑动时间间隔"  textSize="13sp"  inputType="number" />
                            </horizontal>
 
                            <horizontal  gravity="center_vertical" padding="5 5" >
                                <View bg="#4F4F4F" h="*" w="10"  ></View>
                                <text w="auto" padding="8 8 8 8" textColor="#222222" textSize="14sp" text="开启无障碍服务" />
                                <Switch id="autoService"  checked="{{auto.service != null}}"  padding="8 8 8 8" />
                            </horizontal>
 
                            <horizontal  gravity="center_vertical" padding="5 5" >
                                <View bg="#4F4F4F" h="*" w="10"  ></View>
                                <text w="auto" padding="8 8 8 8" textColor="#222222" textSize="14sp" text="是否开启控制台" />
                                <Switch id='switchIsShowConsole'  padding="8 8 8 8"  />
                            </horizontal>
                  
                            <horizontal>
                                <button style="Widget.AppCompat.Button.Colored" id="btnSaveWoolConfig" text="保存配置" padding="12dp" w="*" />
                            </horizontal>
                        </vertical>
                    </scroll>
                </frame>
                {/* 第三页*/}
                <frame>
                    <scroll>
                        <vertical>
 
                            <horizontal gravity="center_vertical" padding="5 5"  >
                                <View bg="#00BFFF" h="*" w="10"  ></View>
                                <vertical padding="10 8" h="auto" w="0" layout_weight="1">
                                    <text w="auto" color="#111111" size="16" text="1、需要启动无障碍服务。" />
                                    <text w="auto" color="#111111" size="16" text="2、允许app显示在其他应用的上层。" />
                                </vertical>
                            </horizontal>
                          
                    
                        </vertical>
                    </scroll>
                </frame> 
 
            </viewpager>
        </vertical>
        {/* drawer */}
        <vertical layout_gravity="left" bg="#ffffff" w="280">
            <img w="280" h="200" scaleType="fitXY" src="{{rootUrl}}/app/Resources/Images/weixin.jpg" />
            <scroll>
                <list id="menu">
                    <horizontal bg="?selectableItemBackground" w="*">
                        <img w="50" h="50" padding="16"  src="{{icon}}" />
                        <text textColor="black" textSize="15sp" text="{{title}}" layout_gravity="center" />
                    </horizontal>
                </list>
            </scroll>
        </vertical>
    </drawer>
);
 
 
 
//设置滑动页面的标题
ui.viewpager.setTitles(["首页", "配置","说明"]);
//让滑动页面和标签栏联动
ui.tabs.setupWithViewPager(ui.viewpager);
activity.setSupportActionBar(ui.toolbar);
 
 
 
// 用户勾选无障碍服务的选项时，跳转到页面让用户去开启 
//android.permission.SYSTEM_ALERT_WINDOW
ui.autoService.on("check", function (checked) {
    if (checked && auto.service == null) {
        app.startActivity({
            action: "android.settings.ACCESSIBILITY_SETTINGS"
        });
    }
    if (!checked && auto.service != null) {
        auto.service.disableSelf();
    }
});
 
 
// 当用户回到本界面时，resume事件会被触发
ui.emitter.on("resume", function () {
    // 此时根据无障碍服务的开启情况，同步开关的状态
    ui.autoService.checked = auto.service != null;
});
 
initializeRightMenu();
initializeData();
 
/**
 * 薅羊毛
 */
ui.wool.click(function () {
    var appArray = getAppList();
    var foreachTimes = ui.txtForeachTimes.getText();
    var screenSileTimes = ui.txtScreenSileTimes.getText();
    var isShowConsole = ui.switchIsShowConsole.isChecked();
    var timesInterval = ui.txtScreenSileTimesInterval.getText();
    var consoleMessage = "不开启控制台";
    if (isShowConsole) {
        consoleMessage = "开启控制台";
    }
    var tipMessage = "本次共" + appArray.length + "个App参与薅羊毛任务，共循环"
        + ui.txtForeachTimes.getText() + "次,"
        + "屏幕滑动" + screenSileTimes + "次,"
        + consoleMessage
        + "确认执行吗？如果配置不正确请点击取消，前往配置页面进行参数修正！";
    confirm(tipMessage).then(value => {
        //当点击确定后会执行这里, value为true或false, 表示点击"确定"或"取消"
        if (value) {
            threads.start(function () {
                //在新线程执行的代码
                auto.waitFor();
                toastLog("薅羊毛开始请等待进入第一个程序！");
                wool(appArray, foreachTimes, screenSileTimes, isShowConsole, timesInterval);
            });
        } else {
 
        }
    });
});
 
 
 
 
/**
 * 关闭薅羊毛程序
 */
ui.close.click(function () {
    toastLog("薅羊毛线程已经被关闭！");
    threads.shutDownAll();
});
ui.btnSaveWoolConfig.click(function () {
    var woolStorage = storages.create("abc11ss13");//创建本地存储
    woolStorage.put("foreachTimes", "" + ui.txtForeachTimes.getText() + "");
    woolStorage.put("screenSileTimes", "" + ui.txtScreenSileTimes.getText() + "");
    woolStorage.put("isShowConsole", "" + ui.switchIsShowConsole.isChecked() + "");
    woolStorage.put("timesInterval", "" + ui.txtScreenSileTimesInterval.getText() + "");
    toastLog("薅羊毛配置保存成功！");
});
 
 
 
function initializeRightMenu() {
    ui.menu.setDataSource([
        { title: "更新日志",icon:"" },
        { title: "检查更新",icon:"" },
        { title: "教程",icon:"" },
        { title: "关于",icon:"" },
        { title: "退出" ,icon:""}
    ]);
    ui.menu.on("item_click", item => {
        switch (item.title) {
            case "更新日志":
                app.openUrl(rootUrl+"/app/WoolUpgradeLog.html");
                break;
            case "检查更新":
                threads.start(function () {
                    let titileAndVersion = ui.toolbar.getTitle();
                    let appNameAndVersionArray = titileAndVersion.split("v");
                    let appName = appNameAndVersionArray[0];
                    let appVersion = appNameAndVersionArray[1];
                    var url = rootUrl + "/app/WebService.asmx/CheckAppVersion";
                    var version = appVersion;
                    var res = http.post(url, { "appName": appName, "version": version });
                    var returnString = res.body.string();
                    let json = JSON.parse(returnString);
                    if (json.success == "true") {
                        if (json.data.upgrade == "true") {
                            app.openUrl(rootUrl + "/app/WebService.asmx/DownLoadWoolUIApk");
                        } else {
                            toastLog("已经是最新版");
                        }
                    } else {
                        toastLog("请求远端服务器出现异常！请稍后重试！");
                    }
                });
                break;
            case "教程":
                    app.openUrl("https://blog.csdn.net/zy0412326/article/details/104767602");
                    break;
            case "关于":
                dialogs.build({
                    title: "关于",
                    positive: "确定",
                    items: ["薅羊毛UI版纯属个人爱好，如果涉及到侵权请通知作者，作者会尽快解决相应问题。作者邮箱：zy0412326@sina.com"]
                }).on("show", (dialog) => { }).show();
                break;
            case "退出":
                ui.finish();
                break;
        }
    });
    //让工具栏左上角可以打开侧拉菜单
    ui.toolbar.setupWithDrawer(ui.drawer);
} 
 
 
/**
 * 初始化UI和数据
 */
function initializeData() {
    // threads.start(function () {
    //     console.show();
    // });
    var woolStorage = storages.create("abc11ss13");//创建本地存储
    var foreachTimes = woolStorage.get("foreachTimes");
    var screenSileTimes = woolStorage.get("screenSileTimes");
    var isShowConsole = woolStorage.get("isShowConsole");
    var timesInterval = woolStorage.get("timesInterval");
    var appInstallDateTime = woolStorage.get("appInstallDateTime");
    if (foreachTimes != null) {
        ui.txtForeachTimes.setText(foreachTimes);
    }
    if (screenSileTimes != null) {
        ui.txtScreenSileTimes.setText(screenSileTimes);
    }
    if (isShowConsole != null && isShowConsole == "true") {
        ui.switchIsShowConsole.setChecked(true);
    } else {
        ui.switchIsShowConsole.setChecked(false);
    }
    if (timesInterval != null) {
        ui.txtScreenSileTimesInterval.setText(timesInterval);
    }
    if (appInstallDateTime != null) {
        var curTime = new Date();
        var currentTime = new Date(parseInt(curTime.getFullYear()), parseInt(curTime.getMonth() + 1), parseInt(curTime.getDate()), parseInt(curTime.getHours()), parseInt(curTime.getMinutes()), parseInt(curTime.getSeconds()));
        var appInstallDate = appInstallDateTime.toString().split("-");
        var getDay = appInstallDate[2].split(" ")[0]; //天
        var hourMM = appInstallDate[2].split(" ")[1];//时分秒
        var appInstallTime = new Date(parseInt(appInstallDate[0]), parseInt(appInstallDate[1]), parseInt(getDay), hourMM.split(":")[0], hourMM.split(":")[1], parseInt(0));
        var seconds=currentTime - appInstallTime;
        if (seconds/(1000 * 60 * 60 * 24)>3) {
            alert("薅羊毛已经过去3天了,烦请打赏一下作者，您的支持是作者最大的动力！");
            woolStorage.put("appInstallDateTime", "" + getTime() + "");
        }
    } else {
        woolStorage.put("appInstallDateTime", "" + getTime() + "");
    }
}
 
 
/**
 * 获取被选择的app
 */
function getAppList() {
    var appArray = new Array(); //app集合
    var toutiao = ui.toutiao.isChecked();
    if (toutiao) {
        appArray.push(ui.toutiao.getText());
    }
    return appArray;
}
 
 
 
/**
 * 主程序
 * @param {应用列表} appArray 
 * @param {应用打开次数} foreach_count 
 * @param {屏幕滑动次数} see_count 
 * @param {是否显示控制台} isShowConsole 
 * @param {延迟时间} timesInterval 
 */
function wool(appArray, foreach_count, see_count, isShowConsole, timesInterval) {
    threads.start(function () {
        if (isShowConsole) {
            console.show();
            console.setSize(device.width, device.height / 4);
        }
    });
    for (x = 1; x <= foreach_count; x++) {
        for (y = 0; y < appArray.length; y++) {
            let appName = appArray[y];
            toastLog("当前程序：" + appName);
            //app.launchApp(appName);
            sleep(10000);//目前无法判断网速和splash时间，只能延迟久一点。10秒延迟。
            if (appName == '今日头条极速版') {
                
                toutiaorun();
            }
            //滑动次数
            for (z = 1; z <= see_count; z++) {
               
            }
            console.clear();//
        }
    }
 
    toastLog("程序执行完毕3秒后即将关闭...");
    console.error("程序执行完毕3秒后即将关闭...");
    for (let i = 3; i >= 1; i--) {
        console.error(i);
        sleep(1000);
        if (i == 1) {
            home();//返回主页面
            return;
        }
    }
}
 
 
 
/**
 * 一键签到
 * @param {签到程序得app} appArray 
 * @param {是否显示控制台} isShowConsole 
 */
function sign(appArray, isShowConsole) {
 
}
  
/**
 * 屏幕向下滑动并延迟8至12秒
 */
function slideScreenDown(startX, startY, endX, endY, pressTime, timesInterval) {
    swipe(startX, startY, endX, endY, pressTime);
    let randomMin = timesInterval * 1000;
    let randomMax = (parseInt(timesInterval) + 2) * 1000;
    let delayTime = random(randomMin, randomMax);
    sleep(delayTime);
}
 
/**
 *关闭广告
 */
function caiDanCloseAd() {
    if (id("btn_back").exists()) {
        console.log("关闭广告");
        id("btn_back").findOne().click();
    }
}
 
 
/**
 *点击一下屏幕
 */
function clickScreen() {
    var x = device.width / 2;
    var y = device.height / 2;
    click(x, y);
}
 
 
 
 
/**
 *向右侧滑动
 */
function sildeScreenRight() {
    pressTime = random(250, 600);
    swipe(750, 1000, 100, 1000, pressTime);//750, 120, 100, 120, 100
    delayTime = random(25000, 30000);
    sleep(delayTime);
}
 
/**
 * 随机点赞
 * @param {点赞ID}} view_id 
 */
function randomHeart(view_id) {
    index = random(1, 100);
    if (index == 66) {
        var target = id(view_id).findOnce();
        if (target == null) {
            return;
        } else {
            target.click();
            sleep(1000);
        }
    }
}
 
/**
 * 随机关注
 * @param {*} follow_view_id 
 */
function randomFollow(follow_view_id) {
    index = random(1, 100);
    if (index == 66) {
        var target = id(follow_view_id).findOnce();
        if (target == null) {
            return;
        } else {
            target.click();
            sleep(1000);
        }
    }
}
 
 
 
 
/**
 * 随机上滑（防止被判定是机器）上滑后停留时间至少是10S，造成假象表示是对内容感兴趣
 * 点赞和关注先不搞。
 */
function randomUpSildeScreen() {
    let randomIndex = random(1, 50);
    if (randomIndex == 1) {
        console.log("随机上滑被执行了!!!");
        pressTime = random(200, 500);
        swipe(device.width / 2, 500, device.width / 2, device.height - 200, 300);
        delayTime = random(10000, 15000);
        sleep(delayTime);
    }
}
 
/**
 * 连续下滑对上一个无兴趣
 * 其实得和上滑做个排他，既然无兴趣不要在上滑
 */
function randomDownSildeScreen() {
    let randomIndex = random(1, 20);
    if (randomIndex == 1) {
        console.log("连续下滑被执行了");
        swipe(device.width / 2, device.height - 200, device.width / 2, 500, 300);
        sleep(2000);
        swipe(device.width / 2, device.height - 200, device.width / 2, 500, 300);
        delayTime = random(8000, 10000);
        sleep(delayTime);
    }
}
 
 
/**
 *  
 * 获取当前时间
 */
function getTime() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    if (month < 10) {
        month = "0" + month;
    };
    var day = date.getDate();
    if (day < 10) {
        day = "0" + day;
    };
    var hour = date.getHours();
    if (hour < 10) {
        hour = "0" + hour;
    };
    var minute = date.getMinutes();
    if (minute < 10) {
        minute = "0" + minute;
    };
    return year +"-"+ month +"-"+ day +" "+ hour +":"+ minute+":"+ "0";
    
};
 